package controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("test")
public class TestController {

    /**
     * 上传
     * @param usrename
     * @param file--接收文件对象
     * @param session
     */
    @RequestMapping("upload")
    public void upload(String usrename, MultipartFile file, HttpSession session){
        String uuid = UUID.randomUUID().toString();
        String filename = file.getOriginalFilename();
        //获取原始文件名
        String[] split = filename.split("[.]");
        //获取后缀名
        String endName = split[split.length - 1];
        //上传到服务器的文件名
        String serverName = uuid + "." + endName;
        //动态获取路径
        String realPath = session.getServletContext().getRealPath("/img");

        File file1 = new File(realPath);
        //判断路径是否存在，并创建
        if (!file1.exists()){
            file1.mkdir();
        }

        try {
            file.transferTo(new File(file1,serverName));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 下载
     * @param response
     * @param name
     * @throws IOException
     */
    @RequestMapping("/download")
    public void download(HttpServletResponse response, String name) throws IOException {

        response.setHeader("content-disposition","attachment;filename="+name);
        IOUtils.copy(new FileInputStream("\"C:\\Users\\Yao1202\\Pictures\\Saved Pictures\\朱一龙\\1 (1).jpg\""), response.getOutputStream());
    }
}
